<template>
  <view class="container">
    <!-- 表格配置区 -->
   <u-collapse :value="['Table']" v-if="!needInput">
	 <u-collapse-item :title="isOhter ? '连接设备信息' : '设备信息'" name="Table">
		<view class="config-area">
		  <text class="config-text">名称：{{equData.Name}} 类型：{{equData.Type ? equData.Type : equData.Ftype}} {{(isOhter && !isInsert) ? ('设备' + ForB2) : ''}}</text>
		  <div style="display: flex;"><text class="config-text" >当前设备：</text>
		    <view style="width: 60px;">
		  	  <u-input v-model="cols" type="number" @input="initGrid" :disabled="!isInsert" />
		    </view>
			 X 
		    <view style="width: 60px;">
			 	<u-input v-model="rows" type="number" :disabled="!isInsert" @input="initGrid" />
			 </view>
		  </div>
		  <view style="display: flex;" v-if="!isOhter || isInsert">
			<u-button type="primary" size="small" :plain="ForB == '前' ? false : true" @click="pickFront">前</u-button>
			<u-button type="primary" size="small" :plain="ForB == '后' ? false : true" @click="pickBehind">后</u-button>
		  </view>
		  <u-button :type="clickSelectButtonType" size="small" @click="toggleClickSelectMode" v-if="isInsert">
			{{ clickSelectButtonText }}
		  </u-button>
		  <u-button size="small" @click="clearSelection"  v-if="isInsert">清除选择</u-button>
		  <!-- <text  v-if="selectCell">点击单元格为{{selectCell}}</text> -->
		</view>

		<!-- 多端兼容的表格 -->
			<view class="table-wrapper">
			  <!-- #ifdef MP-WEIXIN -->
			  <!-- 微信小程序专用表格 -->
			  <view class="wx-table">
				<view 
				  v-for="(row, rowIndex) in tableRows" 
				  :key="rowIndex" 
				  class="wx-table-row"
				>
				  <view 
					v-for="cell in row" 
					:key="cell.number"
					class="wx-table-cell"
					:class="{
					  selected: isPointSelected(cell.number),
					  picked: isPointPicked(cell.number),
					  clicked: isPonitClicked(cell.number),
					  'start-cell': cell.number === visualStartCell,
					  'end-cell': cell.number === visualEndCell
					}"
					@click="handleCellClick(cell.number)"
				  >
					{{ cell.number }}
				  </view>
				</view>
			  </view>
			  <!-- #endif -->
			  
			  <!-- #ifndef MP-WEIXIN -->
			  <!-- 其他平台使用原有表格 -->
			  <view class="grid" :style="gridStyle">
				<view 
				  v-for="cell in cells" 
				  :key="cell.number"
				  class="cell"
				  :class="{
					selected: isPointSelected(cell.number),
					picked: isPointPicked(cell.number),
					clicked: isPonitClicked(cell.number),
					'start-cell': cell.number === visualStartCell,
					'end-cell': cell.number === visualEndCell
				  }"
				  @click="handleCellClick(cell.number)"
				>
				  {{ cell.number }}
				</view>
			  </view>
			  <!-- #endif -->
			  
			  
			</view>
		  </u-collapse-item>
		</u-collapse>
		<!-- <u-collapse v-if="needInput" :value="['Input']">
			<u-collapse-item name='Input' title="描述信息">
				<text class="config-text">设备名称：{{equData.Name}}</text>
				<u--textarea v-model="remark" placeholder="请输入内容" @input="remarkChange"></u--textarea>
			</u-collapse-item>
		</u-collapse> -->
		<u-collapse v-if="needInput" :value="['Input']">
			<u-collapse-item name='Input' title="设备无横纵向信息">
				<text class="config-text">设备名称：{{equData.Name}}</text>
				<u-form ref="uForm" label-width="auto" :rules="rules" :model="lineEqu" >
					<u-form-item label="横向"　:required="true" name="N" prop="N"><u-input v-model="lineEqu.N" type="number"/></u-form-item>
					<u-form-item label="纵向"　:required="true" name="M" prop="M"><u-input v-model="lineEqu.M" type="number"/></u-form-item>
					<u-button @click="apply" throttleTime="500"  type="primary">确定</u-button>
				</u-form>
			</u-collapse-item>
		</u-collapse>
  </view>
</template>

<script>
import {
	getlineequlist,
	GetConnectIds,
	getlinefiber,
	LineequUpdate,
	LinefiberUpdate,
	Used
} from '@/common/api.js'
import throttle from "@/common/throttle.js"
export default {	
  data() {
    return {
      rows: 8,
      cols: 8,
      cells: [],
      points: [], //点击的点整条线
	  picks: [], //所有选择的点
	  clicks: [], //点击的点
      // 微信小程序专用
      tableRows: [],
	  selectCell: null,
	  selectionStart: null, //起始点
	  selectionEnd: null, //结束点
	  visualStartCell: null,
	  visualEndCell: null,
	  clickSelectMode: 'inactive',
	  equData: {}, //设备信息
	  isAdd: false, //判断是否时添加连接状态
	  ForB: '前' ,//设备前后
	  arrs: [], //用来存储选择数组
	  needInput: false,//若无NxM则需填写
	  remark:  '',
	  lineEqu: {
		  N: '',
		  M: '',
	  },
	  rules: {
	  	'N': {
	  		required: true,
	  		message: '请填写横向',
	  		trigger: ['blur']
	  	},
	  	'M': {
	  		required: true,
	  		message: '请填写纵向',
	  		trigger: ['blur']
	  	},
	  },
    }
  },
  props: {
  	equid: {},
	isOhter: {},
	isInsert: {},
	p2: {},
	p2s: {},
	fiberid:{},
	type1: {},
	type2:{},
	ForB2: {}
	// needInput: {}  //若无NxM则需填写
  },
  watch: {
  	isInsert(newv, oldv) {
  		if(newv == true){
			this.points = []
			this.clicks = []
		}
  	},
	equid(newv, oldv){
		this.getData()
	}
  },
  computed: {
    maxCellNumber() {
      return this.rows * this.cols 
    },
    // 其他平台使用grid布局
    gridStyle() {
      return {
        'grid-template-columns': `repeat(${this.cols}, 1fr)`,
        'grid-auto-rows': `minmax(40px, auto)`
      }
    },
	clickSelectButtonType() {
	  return this.isClickSelectModeActive ? 'warning' : 'default'
	},
	clickSelectButtonText() {
	  return this.isClickSelectModeActive ? '取消点击选择' : '点击选择'
	},
	isClickSelectModeActive() {
	  return this.clickSelectMode !== 'inactive'
	},
  },
  methods: {
    initGrid() {
      this.cells = []
      for (let i = 1; i <= this.maxCellNumber; i++) {
        this.cells.push({ number: i })
      }
      
      // #ifdef MP-WEIXIN
      this.prepareWxTable()
      // #endif
      
      // this.loadPointsFromApi()
    },
    
    // 微信小程序专用表格准备
    prepareWxTable() {
      this.tableRows = []
      for (let i = 0; i < this.rows; i++) {
        const row = []
        for (let j = 0; j < this.cols; j++) {
          const index = i * this.cols + j
          if (index < this.cells.length) {
            row.push(this.cells[index])
          }
        }
        this.tableRows.push(row)
      }
    },

    // async loadPointsFromApi() {
    //   try {
    //     // 模拟API数据 - 点对象数组
    //     this.points = [
    //       { Point: '4'},
    //       { Point: '5'},
    //       { Point: '15'},
    //       { Point: '25'}
    //     ]
        
    //     uni.showToast({
    //       title: `已加载 ${this.points.length} 个点`,
    //       icon: 'none'
    //     })
    //   } catch (e) {
    //     this.showError('加载点数据失败: ' + e.message)
    //   }
    // },

    handleCellClick: throttle(function(cellNumber) {
		if (this.isClickSelectModeActive) { //判断是否是选择模式
		  if (this.clickSelectMode === 'selectingStart') {
		    this.selectionStart = cellNumber
		    this.visualStartCell = cellNumber
		    this.clickSelectMode = 'selectingEnd' //选择点击模式变为结束点
		    this.clearVisualEndPoint()
		  } else if (this.clickSelectMode === 'selectingEnd') {
		    this.selectionEnd = cellNumber
		    this.visualEndCell = cellNumber
		    this.selectRange(this.selectionStart, this.selectionEnd)
		    this.clickSelectMode = 'inactive' //选择点击模式变为无效
			this.arrs = []
			this.arrs.push(this.selectionStart)
			this.arrs.push(this.selectionEnd)
			this.$emit('clickTable', this.equData.Id,this.ForB,this.arrs,this.equData.Type)
		    uni.showToast({
		      title: `已选择范围: ${this.selectionStart} 到 ${this.selectionEnd}`,
		      icon: 'success',
		      duration: 1500
		    })
		  }
		}else{  // 非选择模式，查找点击的单元格是否在点数组中
			if(!this.isAdd && !this.isOhter && !this.isInsert){ //添加状态时点击查询无效
				GetConnectIds(this.equData.Id,cellNumber,this.ForB).then(res => {
					if(res.p1s){
						this.clicks = []
						this.points = res.p1s
						this.clicks.push(res.p1)
						this.$emit('loadTable',res)
					}else{
						this.clicks = []
						this.points = []
						uni.showToast({
						  title: '无连接',
						  icon: 'error',
						  duration: 1500
						})
						this.$emit('loadTable', res)
					}
				})
					// const point = this.points.find(p => parseInt(p.Point) === cellNumber)	
					// if (point) {
					//   this.selectCell = cellNumber
					//   uni.showToast({
					//     title: `点击了单元格 ${cellNumber} `,
					//     icon: 'none',
					//     duration: 2000
					//   })
					// } else {
					// 		this.selectCell = null
					//   uni.showToast({
					//     title: `单元格 ${cellNumber} 没有对应的点`,
					//     icon: 'none',
					//     duration: 1500
					//   })
					// }
			}
		}
     
    },350),

    isPointSelected(cellNumber) {
      // 检查当前单元格是否在点数组中
	  if(this.p2s && this.p2s.length!=0){
		  return this.p2s.some(p => parseInt(p) === cellNumber)
	  }else{
		  return this.points.some(p => parseInt(p) === cellNumber)
	  }
    },
	
	isPointPicked(cellNumber) {
		  return this.picks.some(p => parseInt(p) === cellNumber)
	},
	
	isPonitClicked(cellNumber){
		if(this.p2 && this.p2.length!=0){
			return this.p2.some(p => parseInt(p) === cellNumber)
		}else{
			return this.clicks.some(p => parseInt(p) === cellNumber)
		}
	},
	
	toggleClickSelectMode() {
	  if (this.isClickSelectModeActive) { //如果有模式，清空所有选择，退出选择模式
	    this.resetClickSelection()
	  } else {
		  this.selectionStart = null
		  this.selectionEnd = null
		  this.visualStartCell = null
		  this.visualEndCell = null
		  this.picks = []
	    this.clickSelectMode = 'selectingStart' //选择点击模式变为起始点 
	    uni.showToast({
	      title: '请依次点击起始点和结束点',
	      icon: 'none',
	      duration: 2000
	    })
	  }
	  this.isAdd = true
	},
	
	resetClickSelection() {
	  this.clickSelectMode = 'inactive'
	  this.selectionStart = null
	  this.selectionEnd = null
	},
	
	clearVisualEndPoint() {
	  this.visualEndCell = null
	},
	
	selectRange(start, end) {
	  const min = Math.min(start, end)
	  const max = Math.max(start, end)
	  
	  this.picks = []
	  for (let i = min; i <= max; i++) {
		this.picks.push(i)
	  }
	  // this.visualStartCell = min
	  // this.visualEndCell = max
	  
	},
	
	clearSelection() {
	  this.selectionStart = null
	  this.selectionEnd = null
	  this.visualStartCell = null
	  this.visualEndCell = null
	  this.picks = []
	  this.isAdd = false
	  this.clickSelectMode = 'inactive'
	  this.clicks = []
	  this.points = []
	  this.$emit('clickTable', '','',[])
	  this.$emit('loadTable', '', '', [], [])
	  uni.showToast({
	    title: '已清除所有选择',
	    icon: 'none'
	  })
	},
	async getequ(id) {
		let para = {
			Parameters: [],
		}
		para.Parameters.push({
			FieldName: "Id",
			ConditionalType: "Equal",
			FieldValue: id
		})
		await getlineequlist(para).then(res => {
			if(res.count > 0){
				this.equData = res.data[0]
				if(res.data[0].NxM){
					this.needInput = false
					this.rows = res.data[0].NxM.split(',')[1] || 6
					this.cols = res.data[0].NxM.split(',')[0] || 6
					this.initGrid()
				}else{
					this.needInput = true
				}
			}else{
				uni.$u.toast('连接设备/缆线已删除，请删除连接！')
			}
		})
	},
	async getfiber(id) {
		let para = {
			Parameters: [{
				FieldName: "Id",
				ConditionalType: "Equal",
				FieldValue: id
			}],
			orderBys: ["Id"],
		}
		await getlinefiber("",para).then(res => {
			if(res.count > 0){
				this.equData = res.data[0]
				if(res.data[0].NxM){
					this.needInput = false
					this.rows = res.data[0].NxM.split(',')[1] || 6
					this.cols = res.data[0].NxM.split(',')[0] || 6
					this.initGrid()
				}else{
					this.needInput = true
				}
			}else{
				uni.$u.toast('连接设备/缆线已删除，请删除连接！')
			}
		})
	},
	pickFront(){
		if(this.ForB == '前')
		return
		this.ForB = '前'
		this.clearSelection()
		if(!this.isInsert)
		this.getUsed()
	},
	pickBehind(){
		if(this.ForB == '后')
		return
		this.ForB = '后'
		this.clearSelection()
	},
	getData(){
		if(this.type2 && this.type2 == '缆线' || this.type1 == '缆线'){
			this.getfiber(this.equid)
		}else{
			this.getequ(this.equid)
		}
		if(!this.isInsert && !this.isOhter)
		this.getUsed()
	},
	apply(){
		this.$refs.uForm.validate().then(res => {
				this.equData.NxM = this.lineEqu.N + ',' + this.lineEqu.M
				if(this.equData.Ftype){
					LinefiberUpdate(this.equData)
					this.getData()
				}else{
					LineequUpdate(this.equData)
					this.getData()
				}
			}).catch(errors => {
				uni.$u.toast('请填写必填参数！')
			})	
	},
	equUpdata(){
		this.equData.NxM = this.cols + ',' + this.rows
		if(this.equData.Ftype){
			LinefiberUpdate(this.equData)
			this.getData()
		}else{
			LineequUpdate(this.equData)
			this.getData()
		}
	},
	getUsed(){
		Used(this.equid,this.ForB).then(res => {
			this.points = res
		})
	}
  },
  // onLoad() {
   
  // },
  mounted() {
	this.getData()
	// const pages = getCurrentPages()
	// const currentPage = pages[pages.length - 1]
	  // this.rows = parseInt(currentPage.options.rows) || 6
	  // this.cols = parseInt(currentPage.options.cols) || 6
  },
  onReady() {
  		// #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU 
  		//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		if(this.needInput)
      	this.$refs.uForm.setRules(this.rules)
  		// #endif
  },
}
</script>

<style scoped>
/* 通用样式 */
.container {
  padding: 12px;
  display: flex;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;
}

.config-area {
  margin-bottom: 12px;
  width: 100%;
}

.config-text {
  font-size: 16px;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.range-text {
  font-size: 14px;
  color: #666;
  display: block;
  margin-bottom: 8px;
}

.error-text {
  font-size: 14px;
  color: #ff6b6b;
  display: block;
  margin-bottom: 8px;
}

/* .selected-range {
  font-size: 14px;
  color: #5c7cfa;
  display: block;
  font-weight: bold;
  margin-bottom: 8px;
} */

.table-wrapper {
  width: 100%;
  overflow: auto;
}

.start-cell::after {
  content: "起";
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 10px;
  color: white;
  background: #ff6b6b;
  border-radius: 50%;
  width: 14px;
  height: 14px;
  line-height: 14px;
  text-align: center;
}

.end-cell::after {
  content: "终";
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 10px;
  color: white;
  background: #5c7cfa;
  border-radius: 50%;
  width: 14px;
  height: 14px;
  line-height: 14px;
  text-align: center;
}

/* 非微信平台使用grid布局 */
/* #ifndef MP-WEIXIN */
.grid {
  display: grid;
  width: 100%;
  min-width: 100%;
}

.cell {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
  border: 1px solid #f0f0f0;
  font-size: 14px;
  padding: 4px;
  word-break: break-all;
  box-sizing: border-box;
  position: relative;
  cursor: pointer;
}

 .selected {
	  background-color: #7ec699;
	  font-weight: bold;
}

 .picked {
	background-color: #aaffff;
	font-weight: bold;
}

 .clicked {
	background-color: #ff5500 ; 
	font-weight: bold;
}


/* #endif */

/* 微信小程序专用样式 */
/* #ifdef MP-WEIXIN */
.wx-table {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.wx-table-row {
  display: flex;
  width: 100%;
  margin-bottom: 4rpx;
}

.wx-table-cell {
  flex: 1;
  min-height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #f0f0f0;
  font-size: 32rpx;
  position: relative;
}

.wx-table-cell.selected {
  background-color: #7ec699;
  font-weight: bold;
}

.wx-table-cell.picked {
	background-color: #aaffff;
	font-weight: bold;
}

.wx-table-cell.clicked {
	background-color: #ff5500 ; 
	font-weight: bold;
}
/* #endif */

/* 响应式调整 */
@media (max-width: 480px) {
  /* #ifndef MP-WEIXIN */
  .cell {
    font-size: 12px;
  }
  /* #endif */
  
  /* #ifdef MP-WEIXIN */
  .wx-table-cell {
    font-size: 12px;
  }
  /* #endif */
}

</style>